package com.sqsf.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//spring与web环境整合-进阶代码书写
//书写监听器 监听服务器的启动与关闭实现spring容器的创建与销毁
//当服务器启动时 读取spring核心配置文件创建spring容器对象 并将其存入servletContext作用域中
//当服务器关闭时 获取作用域中spring容器对象 调用close方法关闭容器
//servlet使用时 获取作用域中spring容器对象 获取对应对象进行使用
@WebServlet("/b")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //servlet使用时 获取作用域中spring容器对象 获取对应对象进行使用
        ServletContext servletContext = req.getServletContext();
        ClassPathXmlApplicationContext applicationContext = (ClassPathXmlApplicationContext) servletContext.getAttribute("spring");
        User bean = applicationContext.getBean(User.class);
        System.out.println(bean);
    }
}
